package com.xiaozhichao.databafflesys.admin.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaozhichao.databafflesys.common.domain.CommonConstant;
import com.xiaozhichao.databafflesys.common.domain.ExceptionEnums;
import com.xiaozhichao.databafflesys.common.domain.PageHelper;
import com.xiaozhichao.databafflesys.common.domain.ResultVo;
import com.xiaozhichao.databafflesys.repository.model.BaffleConfig;
import com.xiaozhichao.databafflesys.repository.model.BaffleInterface;
import com.xiaozhichao.databafflesys.repository.model.BaffleMessage;
import com.xiaozhichao.databafflesys.repository.service.BaffleConfigService;
import com.xiaozhichao.databafflesys.repository.service.BaffleInterfaceService;
import com.xiaozhichao.databafflesys.repository.service.BaffleMessageService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xiaozhichao
 * @since 2021-03-23
 */
@Controller
@RequestMapping("/baffleInterface")
public class BaffleInterfaceController {
    
    @Autowired
    BaffleInterfaceService interfaceService;

    @Autowired
    BaffleMessageService messageService;

    @Autowired
    BaffleConfigService configService;

    @RequestMapping("/selectPage")
    @ResponseBody
    public ResultVo selectPage(BaffleInterface entry, PageHelper helper){
        IPage<BaffleInterface> page = new Page<>(helper.getPage(),helper.getLimit());
        QueryWrapper<BaffleInterface> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(!StringUtils.isEmpty(entry.getCode()),BaffleInterface::getCode,entry.getCode())
                .eq(!StringUtils.isEmpty(entry.getAppCode()),BaffleInterface::getAppCode,entry.getAppCode())
                .eq(!StringUtils.isEmpty(entry.getEnvCode()),BaffleInterface::getEnvCode,entry.getEnvCode())
                .eq(!StringUtils.isEmpty(entry.getDatasourceCode()),BaffleInterface::getDatasourceCode,entry.getDatasourceCode())
                .eq(!StringUtils.isEmpty(entry.getReqType()),BaffleInterface::getReqType,entry.getReqType())
                .eq(!StringUtils.isEmpty(entry.getResType()),BaffleInterface::getResType,entry.getResType())
                .eq(!StringUtils.isEmpty(entry.getCode()),BaffleInterface::getCode,entry.getCode())
                .like(!StringUtils.isEmpty(entry.getName()),BaffleInterface::getName,entry.getName());
        IPage<BaffleInterface> pageResult = interfaceService.page(page, wrapper);
        List<BaffleInterface> result = pageResult.getRecords();

        // 路由站点信息
        QueryWrapper<BaffleConfig> wrapperConfig = new QueryWrapper<>();
        wrapperConfig.lambda()
                .eq(true,BaffleConfig::getCode,CommonConstant.route_address);
        BaffleConfig config = configService.getOne(wrapperConfig);
        String route_address = Objects.nonNull(config) ? config.getNote() : "";

        Iterator<BaffleInterface> iterator = result.iterator();
        while(iterator.hasNext()){
            BaffleInterface next = iterator.next();
            if(CommonConstant.file.equals(next.getResType())){
                next.setUri(route_address + CommonConstant.uri_spilt + "routeFile" + next.getUri());
            }else{
                next.setUri(route_address + CommonConstant.uri_spilt + "route" + next.getUri());
            }
        }
        return ResultVo.getResult(ExceptionEnums.SUCCESS,pageResult.getTotal(),pageResult.getRecords());
    }

    @RequestMapping("/edit")
    @ResponseBody
    public ResultVo edit(@RequestBody BaffleInterface entry){
        BaffleInterface old = interfaceService.getById(entry.getId());
        if(Objects.isNull(old)){
            return ResultVo.getResult(ExceptionEnums.DO_FAIL);
        }

        // 验证是否已使用
        QueryWrapper<BaffleMessage> wrapperUse = new QueryWrapper<>();
        wrapperUse.lambda().eq(Objects.nonNull(entry.getId()),BaffleMessage::getInterfaceId,old.getId());
        int countUse = messageService.count(wrapperUse);
        if(countUse > 0){
            return ResultVo.getResult(ExceptionEnums.DO_FAIL,"该接口已有请求响应配置，不能修改");
        }

        QueryWrapper<BaffleInterface> wrapper = new QueryWrapper<>();
        // 验证name唯一
        wrapper.lambda()
                .eq(!StringUtils.isEmpty(entry.getName()),BaffleInterface::getName,entry.getName())
                .ne(Objects.nonNull(entry.getId()),BaffleInterface::getId,entry.getId());
        int countName = interfaceService.count(wrapper);
        if(countName > 0){
            return ResultVo.getResult(ExceptionEnums.DO_FAIL,"该名称已存在");
        }

        // 验证uri唯一
        wrapper = new QueryWrapper<>(); //{app_code}/{env_code}/{datasource_code}/{code}
        StringBuffer uri_sb = new StringBuffer();
        uri_sb.append(CommonConstant.uri_spilt);
        uri_sb.append(entry.getAppCode() + CommonConstant.uri_spilt);
        uri_sb.append(entry.getEnvCode() + CommonConstant.uri_spilt);
        uri_sb.append(entry.getDatasourceCode() + CommonConstant.uri_spilt);
        uri_sb.append(entry.getCode());
        String uri = uri_sb.toString();
        wrapper.lambda()
                .eq(!StringUtils.isEmpty(entry.getCode())
                                && !StringUtils.isEmpty(entry.getAppCode())
                                && !StringUtils.isEmpty(entry.getEnvCode())
                                && !StringUtils.isEmpty(entry.getDatasourceCode()),
                        BaffleInterface::getUri,uri)
                .ne(Objects.nonNull(entry.getId()),BaffleInterface::getId,entry.getId());
        int countCode = interfaceService.count(wrapper);
        if(countCode > 0){
            return ResultVo.getResult(ExceptionEnums.DO_FAIL,"该应用/坏境/数据源/接口组合已存在配置");
        }
        entry.setUri(uri);

        // 更新
        UpdateWrapper<BaffleInterface> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().eq(BaffleInterface::getId,entry.getId());
        interfaceService.update(entry,updateWrapper);

        return ResultVo.getResult(ExceptionEnums.SUCCESS);
    }

    @RequestMapping("/add")
    @ResponseBody
    public ResultVo add(@RequestBody BaffleInterface entry){
        QueryWrapper<BaffleInterface> wrapper = new QueryWrapper<>();
        // 验证name唯一
        wrapper.lambda()
                .eq(!StringUtils.isEmpty(entry.getName()),BaffleInterface::getName,entry.getName())
                .ne(Objects.nonNull(entry.getId()),BaffleInterface::getId,entry.getId());
        int countName = interfaceService.count(wrapper);
        if(countName > 0){
            return ResultVo.getResult(ExceptionEnums.DO_FAIL,"该名称已存在");
        }

        // 验证uri唯一
        wrapper = new QueryWrapper<>(); //{app_code}/{env_code}/{datasource_code}/{code}
        StringBuffer uri_sb = new StringBuffer();
        uri_sb.append(CommonConstant.uri_spilt);
        uri_sb.append(entry.getAppCode() + CommonConstant.uri_spilt);
        uri_sb.append(entry.getEnvCode() + CommonConstant.uri_spilt);
        uri_sb.append(entry.getDatasourceCode() + CommonConstant.uri_spilt);
        uri_sb.append(entry.getCode());
        String uri = uri_sb.toString();
        wrapper.lambda()
                .eq(!StringUtils.isEmpty(entry.getCode())
                                && !StringUtils.isEmpty(entry.getAppCode())
                                && !StringUtils.isEmpty(entry.getEnvCode())
                                && !StringUtils.isEmpty(entry.getDatasourceCode()),
                        BaffleInterface::getUri,uri)
                .ne(Objects.nonNull(entry.getId()),BaffleInterface::getId,entry.getId());
        int countCode = interfaceService.count(wrapper);
        if(countCode > 0){
            return ResultVo.getResult(ExceptionEnums.DO_FAIL,"该应用/坏境/数据源/接口组合已存在配置");
        }
        entry.setUri(uri);
        // 保存
        interfaceService.save(entry);

        return ResultVo.getResult(ExceptionEnums.SUCCESS);
    }

    @RequestMapping("/del")
    @ResponseBody
    public ResultVo del(@RequestBody Collection<String> idList){
        // 验证是否已使用
        QueryWrapper<BaffleMessage> wrapperUse = new QueryWrapper<>();
        wrapperUse.lambda().in(!CollectionUtils.isEmpty(idList),BaffleMessage::getInterfaceId,idList);
        int countUse = messageService.count(wrapperUse);
        if(countUse > 0){
            return ResultVo.getResult(ExceptionEnums.DO_FAIL,"该接口已有请求响应配置，不能删除");
        }
        // 删除
        QueryWrapper<BaffleInterface> wrapper = new QueryWrapper<>();
        wrapper.lambda().in(!CollectionUtils.isEmpty(idList),BaffleInterface::getId,idList);
        interfaceService.remove(wrapper);

        return ResultVo.getResult(ExceptionEnums.SUCCESS);
    }

    @RequestMapping("/list")
    @ResponseBody
    public ResultVo list(){
        return ResultVo.getResult(ExceptionEnums.SUCCESS,interfaceService.list());
    }


}

